package com.huiyujiaoyu.powertime.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;


import com.huiyujiaoyu.base.BaseFragment;

import java.util.List;

/**
 * Created by yujunlong on 2016/6/27.
 */
public class AllFragmentPagerAdapter extends FragmentPagerAdapter {
    private List<BaseFragment> fragments;
    private FragmentManager fm;
    private List<String> tabTitles;

    public AllFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fm = fm;
    }

    public AllFragmentPagerAdapter(FragmentManager fm,
                                   List<BaseFragment> fragments, List<String> titles) {
        super(fm);
        this.fm = fm;
        this.fragments = fragments;
        this.tabTitles = titles;
    }
    public AllFragmentPagerAdapter(FragmentManager fm,
                                   List<BaseFragment> fragments) {
        super(fm);
        this.fm = fm;
        this.fragments = fragments;
        tabTitles = null;
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    public void setFragments(List<BaseFragment> fragments) {
        if (this.fragments != null) {
            FragmentTransaction ft = fm.beginTransaction();
            for (Fragment f : this.fragments) {
                ft.remove(f);
            }
            ft.commit();
            ft = null;
            fm.executePendingTransactions();
        }
        this.fragments = fragments;
        notifyDataSetChanged();
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        Object obj = super.instantiateItem(container, position);
        return obj;
    }
    //Remove a page for the given position. The adapter is responsible for removing the view from its container
    //防止重新销毁视图
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //如果注释这行，那么不管怎么切换，page都不会被销毁
       // super.destroyItem(container, position, object);
    }
    @Override
    public CharSequence getPageTitle(int position) {
        if(tabTitles!=null){
            return tabTitles.get(position);
        }else{
            return "";
        }

    }
}
